/*
 * Copyright 2017 wshunli
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.example.zhengchaojun.arcgis.moremap;

import android.os.Environment;
import android.util.Log;

import com.esri.arcgisruntime.arcgisservices.TileInfo;
import com.esri.arcgisruntime.data.TileKey;
import com.esri.arcgisruntime.geometry.Envelope;
import com.esri.arcgisruntime.layers.ServiceImageTiledLayer;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MoreMapLayer extends ServiceImageTiledLayer
{
    private MoreMapLayerInfo layerInfo;
    private String cachePath = Environment.getDownloadCacheDirectory().getPath()+ File.separator +"arcgisCache";

    public MoreMapLayer(MoreMapLayerInfo layerInfo, TileInfo tileInfo, Envelope fullExtent)
    {
        super(tileInfo, fullExtent);
        this.layerInfo = layerInfo;
    }

    @Override
    protected String getTileUrl(TileKey tileKey)
    {
        int level = tileKey.getLevel();
        int col = tileKey.getColumn();
        int row = tileKey.getRow();
        String layerUrl = LayerInfoFactory.getLayerUrl(layerInfo, level, col, row);


        Log.e("zcj", "2222222");
        try
        {
            byte[] test = test(layerUrl);
            AddOfflineCacheFile(cachePath,level,col,row,test);
            get
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return layerUrl;
    }

    protected byte[] getTile(TileKey tileKey)
    {
        Log.e("zcj","1111111111");
        return getOfflineCacheFile(cachePath,tileKey.getLevel(),tileKey.getColumn(),tileKey.getRow());
    }

    protected void initLayer()
    {
    }

    // 将图片保存到本地 目录结构可以随便定义 只要你找得到对应的图片
    private byte[] AddOfflineCacheFile(String cachePath, int level, int col, int row, byte[] bytes)
    {
        File file = new File(cachePath);
        if (!file.exists())
        {
            file.mkdirs();
        }
        File levelfile = new File(cachePath + "/" + level);
        if (!levelfile.exists())
        {
            levelfile.mkdirs();
        }
        File rowfile = new File(cachePath + "/" + level + "/" + col + "x" + row
                + ".png");
        if (!rowfile.exists())
        {
            try
            {
                FileOutputStream out = new FileOutputStream(rowfile);
                out.write(bytes);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        return bytes;

    }

    // 从本地获取图片
    private byte[] getOfflineCacheFile(String cachePath, int level, int col, int row)
    {
        byte[] bytes = null;
        File rowfile = new File(cachePath + "/" + level + "/" + col + "x" + row
                + ".png");
        if (rowfile.exists())
        {
            try
            {
                bytes = CopySdcardbytes(rowfile);
            }
            catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        else
        {
            bytes = null;
        }
        return bytes;
    }

    // 读取本地图片流
    private byte[] CopySdcardbytes(File file) throws IOException
    {
        FileInputStream in = new FileInputStream(file);
        ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
        byte[] temp = new byte[1024];
        int size = 0;
        while ((size = in.read(temp)) != -1)
        {
            out.write(temp, 0, size);
        }
        in.close();
        byte[] bytes = out.toByteArray();
        return bytes;
    }

    public byte[] test(String u) throws Exception
    {
        URL url = new URL(u);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        InputStream is = conn.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        final int BUFFER_SIZE = 2048;
        final int EOF = -1;

        int c;
        byte[] buf = new byte[BUFFER_SIZE];

        while (true)
        {
            c = bis.read(buf);
            if (c == EOF)
                break;

            baos.write(buf, 0, c);
        }

        conn.disconnect();
        is.close();

        byte[] data = baos.toByteArray();
        baos.flush();

        return data;
    }

    @Override
    public String getUri()
    {
        return null;
    }
}
